<template>
  <section class="todoapp">
    <TodoHeader @add="addFn"></TodoHeader>
    <TodoMain
      :list="list"
      :type="type"
      @del="delFn"
      @change="changeFn"
      @edit="editFn"
      @set="setFn"
    ></TodoMain>
    <TodoFooter
      :list="list"
      :type="type"
      @clear="clearFn"
      @filter="filterFn"
    ></TodoFooter>
  </section>
</template>

<script>
// 引入组件
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";
export default {
  // 局部注册组件
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("todos")) || [],
      type: localStorage.getItem("todos-type") || "all",
    };
  },
  methods: {
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    changeFn(id) {
      let obj = this.list.find((item) => item.id === id);
      obj.isDone = !obj.isDone;
    },
    addFn(name) {
      this.list.unshift({
        id: Date.now(),
        name,
        isDone: false,
      });
    },
    editFn(id, name) {
      let obj = this.list.find((item) => item.id === id);
      obj.name = name;
    },
    clearFn() {
      this.list = this.list.filter((item) => !item.isDone);
    },
    filterFn(type) {
      this.type = type;
    },
    setFn(value) {
      this.list.forEach((element) => {
        element.isDone = value;
      });
    },
  },
  watch: {
    list: {
      deep: true,
      handler(value) {
        localStorage.setItem("todos", JSON.stringify(value));
      },
    },
    type(value) {
      localStorage.setItem("todos-type", value);
    },
  },
};
</script>

<style>
</style>
